package com.zzh.controller;

import com.zzh.dao.ChatHistoryDao;
import com.zzh.pojo.vo.MessageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

@RestController
@RequestMapping("/ai")
@Slf4j
public class ChatController {
@Autowired//自动注入
    private ChatClient chatClient;
@Autowired
    private ChatHistoryDao chatHistoryDao;
@Autowired
    private ChatMemory chatMemory;

    //定义一个方法，处理前端发送的请求
    @RequestMapping(value = "/chat",produces = "text/html;charset=utf-8")
    public Flux<String> chat(String prompt,String chatId) {
        log.info("接收到用户的输入: {}", prompt);
        log.info("接收到用户的id: {}", chatId);
        //保存会话记录
        chatHistoryDao.save("chat",chatId);
        //动态调用
        return chatClient.prompt()
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .user(prompt).stream().content();
    }
@GetMapping("/history/{type}")
    public List<String> chatHistory(@PathVariable String type){
        log.info("type:{}",type);
        return chatHistoryDao.getChatHistory(type);
    }

    @GetMapping("/history/{type}/{chatId}")
    public List<MessageVO> getChatHistory(@PathVariable String type, @PathVariable String chatId){
        log.info("type:{},chatId:{}",type,chatId);
        List<Message> messageList = chatMemory.get(chatId);
//        List<MessageVO> messageVOList = new ArrayList<>();
//        messageList.forEach(message -> {
//            MessageVO messageVO = new MessageVO(message);
//            messageVOList.add(messageVO);
//        });
        return messageList.stream().map(MessageVO::new).toList();
    }

}
